﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agrement;
using analy;
using System.Threading.Tasks;
using System.Net.Http;
using System.Web.Script.Serialization;
namespace SockLib.Device
{
   public  class JZDevice : IDevice
    {
        /// <summary>
        /// 外部传进来的参数
        /// </summary>
        Dictionary<string, object> Par = new Dictionary<string, object>();
        public void SetParars(Dictionary<string, object> Params)
        {
            Par = Params;
        }

        #region 注册处理
        /// <summary>
        /// <para>收到数据是否满足注册条件</para>
        /// <para>注册格式：11位编号#11位电话号码#1位或2位设备代码</para>
        /// </summary>
        /// <param name="Buffer">Socket收到的数据</param>
        /// <param name="DM">如果成功解析，DM写入相应信息</param>
        /// <returns>True：成功解析，False：未能解析（乱数据）</returns>
        public bool DeviceReg(byte[] Buffer, ref DeviceModel DM, out List<DeviceModel.SendMsg> Sendinfo)
        {
            try
            {
                Sendinfo = new List<DeviceModel.SendMsg>();

                DeviceModel DeviceModel = new DeviceModel();
                byte[] RegMsg;
                if (!RegRull(Buffer, out RegMsg))
                    return false;  //未能解析，返回失败
                byte[] id = new byte[RegMsg.Length];   
                //Array.Copy(RegMsg, id, RegMsg.Length);
                //for (int i = 0; i < id.Length ; i++)
                //{
                //    DeviceModel.Uid += ((char)id[i]).ToString();
                //}

                //if (Convert.ToInt16(DeviceModel.Uid.Substring(0, 1)) == 1)  //第1位是1中心，其他节点
                //    DeviceModel.IsCenter = true;
                //else
                //    DeviceModel.IsCenter = false;
                //DeviceModel.DeviceGroup = DeviceModel.Uid.Substring(1, 4); //获取组号
                //DeviceModel.MobileNo = ASCIIEncoding.ASCII.GetString(Buffer, 12, 11);  //获得手机号
                //DM = DeviceModel;

                string rec = System.Text.Encoding.Default.GetString(Buffer);
                string[] reginfo = rec.Split('@');
                DeviceModel.Uid = reginfo[1];
                if (Convert.ToInt16(DeviceModel.Uid.Substring(0, 1)) == 1)  //第1位是1中心，其他节点
                    DeviceModel.IsCenter = true;
                else
                    DeviceModel.IsCenter = false;
                DeviceModel.DeviceGroup = DeviceModel.Uid.Substring(1, 4); //获取组号
                DeviceModel.MobileNo= reginfo[2];
                DM = DeviceModel;

                DeviceModel.SendMsg DS = new DeviceModel.SendMsg();
                DS.TargetUid = DeviceModel.Uid;
                DS.DeviceOper = Converts.DeviceOper.Register;
                DS.SendBuffer = Buffer;
                if (Convert.ToInt16(DeviceModel.Uid.Substring(0, 1)) == 1)  //第1位是1中心，其他节点
                {
                    DeviceModel.IsCenter = true;                  
                }
                else
                    DeviceModel.IsCenter = false;
                Sendinfo.Add(DS);

                return true;   //返回注册成功
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

       private string  _RegDeviceType;


       /// <summary>
       /// 返回设备类型
       /// </summary>
       /// <returns></returns>
       public string DeviceType()
        {
            return _RegDeviceType;
        }
        
        private bool RegRull(byte[] Buffer, out byte[] reg)
        {
            //注册格式：JZ@8-11位编号#11位电话号码
            string rec = System.Text.Encoding.Default.GetString(Buffer);
            string[] reginfo = rec.Split('@');
            if(reginfo.Length==3  )
            {
                if (reginfo[0]!= "JZ"|| reginfo[2].Length != 11  || reginfo[1].Length<8 || reginfo[1].Length >11)
                {
                    reg = new byte[0];
                    return false;
                }
                else
                {
                    reg = System.Text.Encoding.Default.GetBytes(reginfo[1]);
                    _RegDeviceType="技卓设备";
                    return true;
                }
            }
            else
            {
                reg = new byte[0];
                return false;
            }
        }

        #endregion


        #region 获取数据转发结构
        /// <summary>
        /// 数据转发规则,数据发送给节点
        /// </summary>
        /// <param name="ReceiveData"></param>
        public bool TransferRule(byte[] ReceiveData, out List<DeviceModel.SendMsg> Sendinfo)
        {
            try
            {
                Sendinfo = new List<DeviceModel.SendMsg>();
                List<byte> rec = new List<byte>();
                rec.AddRange(ReceiveData);
                if  (rec.Count > 15)
                {
                    //if(rec[8]==0x5A && rec[9]==0x5A && rec[10]==0 && rec[11]==0 && rec[12]==0x5A)
                    // {
                    //     DeviceModel.SendMsg DA;
                    //    bool B= GetSendBuild(rec.ToArray(), 8,out  DA);
                    //     if (B)
                    //         Sendinfo.Add(DA);
                    //     return B;
                    // }
                    //else
                    // {
                    //     if (rec[11] == 0x5A && rec[12] == 0x5A && rec[13] == 0 && rec[14] == 0 && rec[15] == 0x5A)
                    //     {
                    //         DeviceModel.SendMsg DA;
                    //         bool B = GetSendBuild(rec.ToArray(), 11, out DA);
                    //         if (B)
                    //             Sendinfo.Add(DA);
                    //         return B;
                    //     }
                    // }
                    DeviceModel.SendMsg DA;
                    bool b = GetSendIndex(rec.ToArray(), out DA);
                    if (b)
                        Sendinfo.Add(DA);
                    return b;
                }
                return false;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private bool GetSendIndex(byte[] rec, out DeviceModel.SendMsg DS)
        {
            DS = new DeviceModel.SendMsg();
            for (int i = 8; i < 12; i++)
            {
                if (rec[i] == 0x5A && rec[i+1] == 0x5A && rec[i + 2] == 0 && rec[i + 3] == 0 && rec[i + 4] == 0x5A)
                {
                    DeviceModel.SendMsg DA;
                    bool B = GetSendBuild(rec.ToArray(), i, out DA);
                    if (B)
                    {
                        DS = DA;
                        return B;
                    }
                }
            }
            return false;
        }

        private bool GetSendBuild(byte[] rec,int len,out DeviceModel.SendMsg DS)
        {
      
            List<byte> id = new List<byte>();
            for (int i = 0; i < len; i++)
                id.Add(rec[i]);
            string TargetId = System.Text.Encoding.ASCII.GetString(id.ToArray());
            List<byte> Sendbytes = new List<byte>();
            for (int i = len; i < rec.Length ; i++)
                Sendbytes.Add(rec[i]);
            DS.DeviceOper = Converts.DeviceOper.Transfer;
            DS.TargetUid = TargetId;
            DS.SendBuffer = Sendbytes.ToArray();
            DS.Params  = null;
            return true;

        }

        /// <summary>
        /// 节点数据转发规则
        /// </summary>
        /// <param name="ReceiveData">收到的数据</param>
        /// <param name="uid">GPRS的编号</param>
        /// <param name="Sendinfo">需要转发的结构体</param>
        /// <returns></returns>
        public bool NodeTransferRule(byte[] ReceiveData, string uid, ref DeviceModel.SendMsg[] Sendinfos)
        {
            Device.DeviceModel.SendMsg Sendinfo = new Device.DeviceModel.SendMsg();
            Sendinfo.TargetUid = uid;
            Sendinfo.SendBuffer = ReceiveData;
            Sendinfos = new Device.DeviceModel.SendMsg[1];
            Sendinfos[0] = Sendinfo;
            return true;
        }
        #endregion


        #region 数据转换

        /// <summary>
        /// 心跳包格式,JZ不发送任何心跳
        /// </summary>
        /// <param name="TargetUid">发给的中心模块ID</param>
        /// <param name="uid">在线中心模块ID集合</param>
        /// <returns></returns>
        public List <byte[]> HeartBeatConvert(string TargetUid, string[] uid)
        {
            return null;
        }


        /// <summary>
        /// 发送数据转换
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        public byte[] SendDataConvert(byte[] Data)
        {
            return Data;
        }

        /// <summary>
        /// 接收数据转换
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        public byte[] ReceiveDataConvert(byte[] Data)
        {
            return Data;
        }

        public byte[] DataPacket(DeviceModel.SendMsg SendMsg)
        {
            return SendMsg.SendBuffer;
        }
        #endregion



        #region 心跳包处理
        /// <summary>
        /// 心跳包不做任何转发处理
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public bool IsHeartPack(byte[] Pack)
        {
            if (Pack.Length == 1 && (Pack[0] == 0x2B || Pack[0] == 0xfe))
                return true;
            return false;

        }
        #endregion

        #region 显示LOG区发送数据
        public string SendString(string uid, byte[] msg)
        {
            return Converts.byteToHexStr(msg);
        }
        #endregion 
    }
}
